package com.tbabs.filter;

import com.alibaba.fastjson.JSON;
import com.tbabs.common.BaseContext;
import com.tbabs.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 路径匹配器
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 不需要被拦截的请求
        String[] urls = new String[]{
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        // 获取响应的uri
        String requestURI = request.getRequestURI();

        // 路径匹配
        boolean check = check(urls, requestURI);

        // 不属于拦截路径放行
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }

        // 判断后台是否已登录放行
        if (request.getSession().getAttribute("employee") != null) {
            // 线程存储用户id
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));

            filterChain.doFilter(request, response);
            return;
        }

        // 判断移动端是否已登录放行
        if (request.getSession().getAttribute("user") != null) {
            // 线程存储用户id
            BaseContext.setCurrentId((Long)request.getSession().getAttribute("user"));

            filterChain.doFilter(request, response);
            return;
        }

        // 未登录则通过输出流方式向客户端页面响应数据
        // 前端有request.js的响应拦截器处理跳转，后端只需要回传前端对应的数据即可触发跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    // 路径匹配
    public boolean check(String[] urls, String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
